<template>
  <el-dialog
    v-model="visible"
    title="运营审核"
    width="1000"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
    destroy-on-close
  >
    <template #default>
      <div class="header-title">基础信息</div>
      <Basic ref="basicRef" v-model:value="form" type="operationAudit" />
      <div class="header-title">推荐平台/站点</div>
      <el-tabs class="w-full" type="card" v-model="activeName">
        <el-tab-pane
          :label="item.platform_id_text"
          :name="item.id"
          v-for="(item, index) in product_fee"
          :key="index"
        >
          <template #label>
            {{ item.platform_id_text }} - {{ item.site_text }} ({{
              item.check_status_text
            }})</template
          >
        </el-tab-pane>
      </el-tabs>
      <div class="mb-1 text-[#ff6334]">
        注：若仍需原运营人员审核,则需操作转运营,转回原运营人员审核，审核通过、未通过均表示审核流程结束
      </div>

      <div class="flex justify-between mb-2 items-center">
        <div class="flex-1 flex flex-wrap">
          <div class="flex items-center w-[50%]">
            <div class="w-[80px]">审核结果：</div>
            <el-select
              class="flex-1"
              v-model="current_item.status"
              collapse-tags
              placeholder="请选择"
              clearable
              @change="changeStatus($event, current_item)"
              :disabled="Boolean(current_item.check_status)"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="flex items-center w-[50%] pl-4">
            <div class="w-[80px]">指定运营：</div>
            <select-personnel
              class="flex-1"
              :disabled="!(current_item.status == 3 && current_item.edit_special)"
              v-model="current_item.specified_operation_user_id"
              placeholder="请选择指定运营人员"
            ></select-personnel>
          </div>
          <div class="flex items-center w-[100%] mt-2">
            <div class="w-[80px]">审核备注：</div>
            <el-input
              class="flex-1"
              v-model="current_item.check_remark"
              placeholder="请输入"
              :rows="2"
              type="textarea"
              :disabled="Boolean(current_item.check_status)"
            />
          </div>
        </div>
        <div class="w-[300px] pl-10 text-lg">
          <div class="flex items-center">
            预估产品毛利率：<span class="text-[#ff0000]"
              >{{ calculateProductGross(current_item) }} </span
            >%
            <el-tooltip placement="top">
              <template #content>
                <div v-html="PRODUCT_GROSS_MARGIN_DESCRIPTION"></div>
              </template>
              <svg-icon class="ml-1" icon-class="QuestionFilled"></svg-icon>
            </el-tooltip>
          </div>
          <div>
            预估销售毛利率：<span class="text-[#ff0000]">{{
              calculateSaleGross(current_item)
            }}</span>
            %
          </div>
        </div>
      </div>
      <div class="bg-[var(--base-table-header-bg-color)] p-2">
        <div class="flex flex-wrap base-info">
          <!-- <div class="w-[25%]">
            <span>建议销售价：</span>{{ current_item.selling_price }}
            {{ current_item.currency_name }}
          </div>
          <div class="w-[25%]">
            <span>兑人民币：</span
            >{{
              calculateAgainstRMB(current_item.selling_price, current_item.exchange_rate)
            }}
            CNY
          </div> -->
          <div class="w-[25%]"><span>汇率：</span>{{ current_item.exchange_rate }}</div>
          <div class="w-[25%]">
            <span>采购成本：</span>{{ current_item.purchase_cost }} CNY
          </div>
          <div class="w-[25%]">
            <span>国家：</span>{{ current_item.site_country_code }}
          </div>
          <div class="w-[25%]">
            <span>包装尺寸：</span>{{ current_item.packing_specification.length }} *
            {{ current_item.packing_specification.width }}*
            {{ current_item.packing_specification.height }} cm
          </div>
          <div class="w-[25%]">
            <span>单品毛重：</span>{{ current_item.gross_weight_g }} g
          </div>
        </div>
        <div class="text-[var(--base-placeholder-text-color)]">
          注：运营审核支持直接修改利润试算内容，提交审核后，则编辑内容同步保存成功；
        </div>
      </div>
      <ProfitTrialInfo
        ref="ProfitTrialInfoRef"
        v-model="current_item"
        type="operationAudit"
        :disabled="Boolean(current_item.check_status)"
      ></ProfitTrialInfo>
    </template>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save(formRef)"
        >提交审核</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup lang="jsx">
import api from "../../api";
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Basic from "../BasicInfo/Basic.vue";
import ProfitTrialInfo from "../BasicInfo/ProfitTrialInfo.vue";
import { statusOptions, PRODUCT_GROSS_MARGIN_DESCRIPTION } from "../../data.js";
import {
  calculateProductGross,
  calculateSaleGross,
  calculateAgainstRMB,
} from "../../utils.js";
import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();

const emits = defineEmits(["submit"]);

const data = reactive({
  form: {},
  visible: false,
  loading: false,
  formRef: null,
  product_fee: [],
  activeName: "",
});
const { rules, form, visible, loading, formRef, product_fee, activeName } = toRefs(data);

provide("form", form);
const ProfitTrialInfoRef = ref();

const open = (list, info) => {
  form.value = info;
  product_fee.value = list.map((item) => {
    item.head_channel_id = item.head_channel_id || "";
    item.tail_channel_id = item.tail_channel_id || "";
    return item;
  });
  activeName.value = list[0].id;
  visible.value = true;
  const currency_info = {
    currency_id: current_item.value.currency_id,
    currency: current_item.value.currency_name,
    exchange_rate: current_item.value.exchange_rate,
  };
  nextTick(() => {
    ProfitTrialInfoRef.value?.changeCurrency(currency_info, "open");
  });
};

const current_item = computed(() => {
  return product_fee.value.find((item) => item.id === activeName.value);
});

const save = () => {
  if (!ProfitTrialInfoRef.value) return;
  ProfitTrialInfoRef.value.validate((valid) => {
    if (valid) {
      const data = product_fee.value;
      const messageArray = [];
      data.map((item, index) => {
        if (!item.status && !item.check_status) {
          messageArray.push(`第${index + 1}项，审核结果不能为空`);
        }
        if (item.status === 3) {
          if (!item.specified_operation_user_id && !item.check_status) {
            messageArray.push(
              `第${index + 1}项，当审核结果为转运营时，指定运营人员不能为空`
            );
          }
        }
        if (item.status === 2 && !item.check_remark) {
          messageArray.push(`第${index + 1}项，当审核结果为未通过时，审核备注必填`);
        }
      });

      if (messageArray && messageArray.length) {
        ElMessageBox({
          title: "提示",
          message: () => <div>{messageArray.map((d) => h("p", null, d))}</div>,
        });
        return;
      }
      const params = data
        .filter((i) => i.check_status == 0)
        ?.map((item) => {
          return {
            ...item,
            check_status: item.status,
            type: 1,
          };
        });

      if (params.length === 0) {
        return ElMessage.error("该任务无需您审核，请核对后操作");
      }

      loading.value = true;
      api
        .operationReview({ params: params })
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("审核成功!");
            close(true);
          } else {
            ElMessage.warning(res.message);
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

const changeStatus = (val, row) => {
  if (val != 3) {
    row.specified_operation_user_id = "";
  }
};
const close = () => {
  form.value = {};
  visible.value = false;
};

onMounted(() => {
  if (!commonStore.currencyOptions) {
    commonStore.getCurrencyList();
  }
});
defineExpose({ open });
</script>
<style lang="scss" scoped>
.base-info {
  > div {
    padding: 4px 0;
  }
  span {
    color: var(--base-sub-text-color);
  }
}
</style>
